<template>
  <div class="goodsdetailbox">
    <!-- <button @click="getinfohandle"></button> -->
    <Editor
      :disabled="this.temp.contentIsPublic == 0"
      :id="tinymceId"
      ref="inputValueRef"
      v-model="addgoodsinfo.goods.details"
      :init="editorInit"
    />
  </div>

  <!-- 图片信息获取到的是 base64 -->
</template>
<script>
import contentApi from "@/api/release/content";
import columnApi from "@/api/release/column";
import { cloud } from "@/framework/utils/request";
import { getToken } from "@/framework/utils/auth";
import Editor from "@tinymce/tinymce-vue";
import { checkNumber } from "@/framework/utils/validate";
export default {
  name: "GoodsDetails",
  props: {
    // addgoodsinfo.goods.details
    addgoodsinfo: {
      type: Object,
      required: true,
    },
  },
  components: {
    Editor,
  },
  data() {
    // const validateNum = (rule, value, callback) => {
    //     if (!value) {
    //         callback('请输入数字')
    //     } else if (checkNumber(value) === false) {
    //         callback("格式错误，请输入数字")
    //     } else {
    //         callback()
    //     }
    // }
    const validateNum = (rule, value, callback) => {
      if (value && !checkNumber(value)) {
        callback("格式错误，请输入数字");
      } else {
        callback();
      }
    };
    return {
      parentColumnName: "",
      visible: false,
      defaultId: [],
      treePopover: [],
      dialogImageUrl: "",
      dialogVisible: false,
      showBtnImg: true,
      noneBtnImg: false,
      loading: false,
      uploadFileUrl:
        process.env.VUE_APP_BASE_API +
        cloud.file +
        "/sysFileInfo/upload?secretFlag=N",
      uploadHeaders: {
        Authorization: getToken(),
      },
      limitCountImg: 1,
      picFileList: [],
      fileList: [],
      subjectDictList: [],
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "修改内容",
        create: "新增内容",
      },
      fileTipText:
        "支持格式:xls、xlsx、doc、docx、ppt、pptx、txt、pdf、rar、zip、jpg、png、tif、bmp、svg，<br/>单个文件最大不能超过10MB且最多能上传10个文件",
      videoTipText:
        "支持格式:mp4、avi、mpeg 单个文件最大不能超过500MB且最多能上传1个视频文件",
      relateContentList: [],
      temp: {
        contentTitle: "",
        contentKeyword: "",
        contentDesc: "",
        subjectDictId: "",
        contentType: 1,
        contentJumpLink: "",
        fileIds: "",
        contentIsSend: 0,
        content: "",
        columnId: "",
        picFileId: "",
        fieldList: [],
        dictTypeList: [],
        relateContentSelect: [],
        relateContentIds: "",
        contentSort: "",
      },
      strRules: [
        {
          required: true,
          message: "该字段不能为空",
          trigger: "blur",
        },
        {
          pattern: /^[^#@%&*¥$*]+$/,
          message: "不要输入特殊字符",
        },
      ],
      numRules: [
        {
          required: false,
          trigger: "blur",
          validator: validateNum,
        },
      ],
      columnRules: [
        {
          required: true,
          trigger: "change",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择关联栏目"));
            } else {
              callback();
            }
          },
        },
      ],
      dictRules: [
        {
          required: true,
          trigger: "change",
          validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error("请选择筛选分类"));
            } else {
              callback();
            }
          },
        },
      ],
      dateRules: [
        {
          type: "date",
          required: true,
          trigger: "change",
          message: "请选择时间",
        },
      ],
      rules: {
        content: [
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请填写发布内容"));
              } else {
                callback();
              }
            },
          },
        ],
        contentSort: [
          {
            required: false,
            trigger: "blur",
            validator: validateNum,
          },
        ],
        fileIds: [
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请至少上传一个附件"));
              } else {
                callback();
              }
            },
          },
        ],
        contentJumpLink: [
          {
            required: true,
            message: "请输入跳转链接",
            trigger: "blur",
          },
        ],
        columnId: [
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请选择所属栏目"));
              } else {
                callback();
              }
            },
          },
        ],
        contentTitle: [
          {
            required: true,
            message: "请输入内容标题",
            trigger: "blur",
          },
          {
            pattern: /^[^#@%&*¥$*]+$/,
            message: "不要输入特殊字符",
          },
        ],
        contentKeyword: [
          {
            required: true,
            message: "请输入关键词",
            trigger: "blur",
          },
          {
            pattern: /^[^#@%&*¥$*]+$/,
            message: "不要输入特殊字符",
          },
        ],
        contentDesc: [
          {
            required: true,
            message: "请输入内容简介",
            trigger: "blur",
          },
          {
            pattern: /^[^#@%&*¥$*]+$/,
            message: "不要输入特殊字符",
          },
        ],
        subjectDictId: [
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请选择主题分类"));
              } else {
                callback();
              }
            },
          },
        ],
        contentType: [
          {
            required: true,
            message: "请选择内容类型",
            trigger: "blur",
          },
        ],
        picFileId: [
          {
            required: true,
            trigger: "change",
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error("请上传图片"));
              } else {
                callback();
              }
            },
          },
        ],
      },
      tinymceId: "",
      defaultProps: {
        children: "children",
        label: "label",
        disabled: "disabled",
      },
      currentColumn: {},
      fileType: ["jpg", "JPG", "png", "PNG"],
      fileSize: 500,
    };
  },
  computed: {
    theme() {
      return this.$store.getters.theme;
    },
    themeActive() {
      return this.$store.state.settings.theme;
    },
    lightTheme() {
      return this.theme + "19";
    },
    editorInit() {
      return {
        menubar: false,
        branding: false,
        // language_url: '/Tinymce/zh_CN.js',
        language: "zh_CN",
        // skin_url: '/Tinymce/skins/ui/oxide',
        height: this.height,
        body_class: "panel-body ",
        plugins: [
          "code",
          "print",
          "preview",
          "fullscreen",
          "paste",
          "searchreplace",
          "save",
          "autosave",
          "link",
          "autolink",
          "image",
          "imagetools",
          "media",
          "table",
          "codesample",
          "lists",
          "advlist",
          "hr",
          "charmap",
          "emoticons",
          "anchor",
          "directionality",
          "pagebreak",
          "quickbars",
          "nonbreaking",
          "visualblocks",
          "visualchars",
          // 'wordcount'
        ].join(" "),
        toolbar: [
          "fullscreen",
          "preview",
          "code",
          "|",
          "undo",
          "redo",
          "|",
          "forecolor",
          "backcolor",
          "|",
          "bold",
          "italic",
          "underline",
          "strikethrough",
          "|",
          "alignleft",
          "aligncenter",
          "alignright",
          "alignjustify",
          "|",
          "outdent",
          "indent",
          "|",
          "numlist",
          "bullist",
          "|",
          "formatselect",
          "fontselect",
          "fontsizeselect",
          "|",
          "link",
          "image",
          "media",
          "emoticons",
          "charmap",
          "anchor",
          "pagebreak",
          "codesample",
          "|",
          "ltr",
          "rtl",
        ].join(" "),
        draggable_modal: true,
        toolbar_mode: "sliding",
        images_upload_handler: (blobInfo, success) => {
          // success('data:image/jpeg;base64,' + blobInfo.base64())
          // 改为自定义上传
          const formData = new FormData();
          formData.append("file", blobInfo.blob());
          formData.append("secretFlag", "N");
        },
        file_picker_types: "media",
        file_picker_callback: () => {},
      };
    },
  },
  created() {
    this.initData();
  },
  methods: {
    emitdetail() {
      return this.temp.content;
    },
    getinfohandle() {
      ////console.log('getinfo',this.addgoodsinfo.goods.details);
    },
    renderContent(h, { node, data, store }) {
      return (
        <div style="{node.disabled?'color: #c1c1c1;cursor: not-allowed': 'color: #000'}">
          <span>{node.label}</span>
        </div>
      );
    },

    initData() {
      // contentApi.findDictForTheme().then((res) => {
      //   this.subjectDictList = res.data;
      // });
    },
    tinyInitHandler() {
      this.$nextTick(() => {
        this.$refs.focusMe.focus();
      });
    },
    handleBeforeUploadPic(file) {
      if (this.fileType) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        const isTypeOk = this.fileType.some((type) => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
        if (!isTypeOk) {
          this.$message.error(
            `文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`
          );
          return false;
        }
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} KB!`);
          return false;
        }
      }
      return true;
    },
    // 上传失败
    handleUploadPicError(err, file, fileList) {
      this.uploadLoading = false;
      this.$message.error(err);
    },
    // 上传成功回调
    handleUploadPicSuccess(res) {
      this.temp.picFileId = res.data.fileId;
      this.uploadLoading = false;
      this.$dtMessage({
        title: "成功",
        message: "上传成功",
        type: "success",
        duration: 2000,
      });
    },
    onPicExceed(files, fileList) {
      this.dtMessage.error("单次只能上传一个文件!");
    },
    handleRemovePic(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limitCountImg;
      this.temp.picFileId = "";
    },
    handleImgChange(file, fileList) {
      this.noneBtnImg = fileList.length >= this.limitCountImg;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    onPicProgress(event, file, fileList) {
      this.uploadLoading = true;
    },
    //打开窗口
    openContent(row, type) {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].resetFields();
      }
      this.dialogFormVisible = true;
      if (type == "add") {
        this.dialogStatus = "create";
      } else if (type == "update") {
        this.dialogStatus = "update";
        contentApi.detail(row.contentId).then((res) => {
          let tempCache = Object.assign({}, res.data);
          columnApi.detail(tempCache.columnId).then(async (res1) => {
            if (res1.data.fieldList) {
              res1.data.fieldList.forEach((item) => {
                item.value = tempCache.contentEx[item.fieldCode];
              });
              tempCache.fieldList = res1.data.fieldList;
            }
            if (res.data.relateContentIds) {
              await contentApi
                .contentListByColumnId({ columnId: res1.data.relateColumn })
                .then((res2) => {
                  this.relateContentList = res2.data;
                  let relateContentSelect =
                    res.data.relateContentIds.split(",");
                  tempCache.relateContentSelect = relateContentSelect;
                });
            }
            if (res1.data.dictTypeList) {
              let dictTypeListNew = res1.data.dictTypeList;
              if (res.data.dictTypeList) {
                ////console.log("res.data.dictTypeList", res.data.dictTypeList);
                let dictTypeListArr = JSON.parse(res.data.dictTypeList);
                dictTypeListArr.forEach((item) => {
                  dictTypeListNew.forEach((item1) => {
                    if (item.dictTypeCode == item1.dictTypeCode) {
                      this.$set(item1, "value", item.value);
                    }
                  });
                });
                tempCache.dictTypeList = dictTypeListNew;
              }
            }
            if (res.data.picFileId) {
              this.picFileList.push({
                url:
                  process.env.VUE_APP_BASE_API +
                  cloud.file +
                  "/sysFileInfo/previewByObjectName?" +
                  "fileBucket=defaultBucket" +
                  "&fileObjectName=" +
                  res.data.picFileInfo.fileObjectName,
              });
              this.showBtnImg = false;
              this.noneBtnImg = true;
            }
            if (res.data.fileList) {
              let fileIds = "";
              res.data.fileList.map((detail, index) => {
                this.fileList.push({
                  name: detail.fileOriginName,
                  response: {
                    data: {
                      fileId: detail.fileId,
                      fileUrl: detail.fileUrl,
                      fileOriginName: detail.fileOriginName,
                      fileObjectName: detail.fileObjectName,
                      filelength: detail.filelength,
                      uid: detail.id,
                    },
                  },
                });
                fileIds += detail.fileId;
                if (index != res.data.fileList.length - 1) {
                  fileIds += ",";
                }
              });
              tempCache.fileIds = fileIds;
            }
            this.parentColumnName = res1.data.columnName;
            this.cacheData = JSON.stringify(tempCache);
            this.temp = JSON.parse(JSON.stringify(tempCache));
          });
        });
      }
    },
    // 修改内容请求
    updateData() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const tempData = Object.assign({}, this.temp);
          if (
            tempData.relateContentSelect &&
            tempData.relateContentSelect.length > 0
          ) {
            let relateContentIds = "";
            tempData.relateContentSelect.forEach((item, index) => {
              ////console.log("item", item);
              relateContentIds += item;
              if (index != tempData.relateContentSelect.length - 1) {
                relateContentIds += ",";
              }
            });
            this.$set(tempData, "relateContentIds", relateContentIds);
          }
          if (this.cacheData === JSON.stringify(tempData)) {
            this.dialogFormVisible = false;
            this.loading = false;
          } else {
            try {
              await contentApi.edit(tempData);
              this.$parent.getList();
              this.dialogFormVisible = false;
              this.$dtMessage({
                title: "成功",
                message: "更新成功",
                type: "success",
                duration: 2000,
              });
              this.loading = false;
            } catch (error) {
              this.loading = false;
            }
          }
        }
        this.loading = false;
      });
    },
    // 创建内容发布
    async createData() {
      this.$refs["dataForm"].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          const tempData = Object.assign({}, this.temp);
          if (tempData.relateContentSelect.length > 0) {
            let relateContentIds = "";
            tempData.relateContentSelect.forEach((item, index) => {
              ////console.log("item", item);
              relateContentIds += item;
              if (index != tempData.relateContentSelect.length - 1) {
                relateContentIds += ",";
              }
            });
            this.$set(tempData, "relateContentIds", relateContentIds);
          }
          try {
            await contentApi.add(tempData);
            this.$parent.getList();
            this.dialogFormVisible = false;
            this.$dtMessage({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000,
            });
            this.loading = false;
          } catch (error) {
            this.loading = false;
          }
        }
        // this.loading = false
      });
    },
    resetTemp() {
      this.temp = {
        contentTitle: "",
        contentKeyword: "",
        contentDesc: "",
        subjectDictId: "",
        contentType: 1,
        contentJumpLink: "",
        fileIds: "",
        contentIsSend: 0,
        content: "",
        columnId: "",
        picFileId: "",
        fieldList: [],
        dictTypeList: [],
        relateContentSelect: [],
        relateContentIds: "",
        contentSort: "",
      };
      if (this.$refs["contentFiles"]) {
        this.$refs["contentFiles"].clearFiles();
      }
      this.columnName = "";
      this.parentColumnName = "";
      this.picFileList = [];
      this.fileList = [];
      this.relateContentList = [];
      if (this.$refs["contentPic"]) {
        this.$refs["contentPic"].clearFiles();
        this.showBtnImg = true;
        this.noneBtnImg = false;
      }
    },
    beforeHandleSuccess(file) {
      let arr = "";
      let isLt2M = "";
      let limitSize = "";
      if (this.temp.contentType == 4) {
        arr = [".mp4", ".avi", ".mpeg"];
        isLt2M = file.size / 1024 / 1024 < 500;
        limitSize = "300";
      } else {
        arr = [
          ".PDF",
          ".pdf",
          ".xls",
          ".xlsx",
          ".doc",
          ".docx",
          ".ppt",
          ".pptx",
          ".txt",
          ".rar",
          ".zip",
          "jpg",
          "png",
          "tif",
          "bmp",
          "svg",
        ];
        isLt2M = file.size / 1024 / 1024 < 10;
        limitSize = "10";
      }
      const s = arr.filter((el) => {
        return file.name.toLowerCase().lastIndexOf(el) > 0;
      });
      if (s.length == 0) {
        this.$message.error("上传文件格式不正确");
        return false;
      }

      if (!isLt2M) {
        this.$message.error("上传文件大小不能超过" + limitSize + "MB!");
        return false;
      }
      if (file.name.length > 50) {
        this.$message.error("文件名称过长，建议长度在50字符内。");
        return false;
      }
      var flag = false;
      this.fileList.forEach((element) => {
        if (file.name === element.name) {
          flag = true;
          return flag;
        }
      });
      if (flag) {
        this.$message.error("上传文件重复！");
        return false;
      }
      return true;
    },
    uploadSuccess(response, file, fileList) {
      this.fileList = fileList;
      let fileIds = "";
      this.fileList.forEach((item, index) => {
        fileIds += item.response.data.fileId;
        if (index != this.fileList.length - 1) {
          fileIds += ",";
        }
      });
      this.$set(this.temp, "fileIds", fileIds);
      this.$dtMessage({
        title: "成功",
        message: "上传成功",
        type: "success",
        duration: 2000,
      });
    },
    uploadError(err, file, fileList) {
      this.$dtMessage({
        title: "失败",
        message: err,
        type: "error",
        duration: 2000,
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning("已超过文件上传个数限制！");
    },
    remove(file, fileList) {
      this.fileList = fileList;
    },
    loadPopover(tree, resolve) {
      let columnId = "";
      if (!tree.data || tree.data.length == 0) {
        columnId = 0;
      } else {
        columnId = tree.data.id;
      }
      columnApi
        .columnLazyAntdvAll({ columnId: columnId, isDataScope: true })
        .then((res) => {
          const data = res.data;
          resolve(data);
        });
    },
    // 选择栏目
    selectParentColumn(data) {
      if (data.disabled) {
        this.$message.error("该栏目类型为目录，不能选择该节点！");
        return;
      }
      this.visible = false;
      this.temp.columnId = data.id;
      this.parentColumnName = data.label;
      this.currentColumn = data;
      this.defaultId = [];
      this.defaultId.push(this.temp.columnId);
      this.$refs.columnParentRef.clearValidate();
      columnApi.detail(data.id).then((res) => {
        if (res.data.fieldList) {
          this.temp.fieldList = res.data.fieldList;
        }
        if (res.data.dictTypeList) {
          this.temp.dictTypeList = res.data.dictTypeList;
        }
        this.temp.contentType = res.data.columnContentType;
        if (res.data.relateColumn) {
          contentApi
            .contentListByColumnId({ columnId: res.data.relateColumn })
            .then((res1) => {
              this.relateContentList = res1.data;
              ////console.log(this.relateContentList);
            });
        }
      });
    },

    columnInput() {
      columnApi
        .columnLazyAntdvAll({
          columnId: 0,
          columnName: this.parentColumnName,
          isDataScope: true,
        })
        .then((res) => {
          this.treePopover = res.data;
        });
      if (this.parentColumnName == "") {
        this.parentColumnName = "";
        this.temp.columnId = "";
      }
    },
    columnFocus() {
      const param = this.currentColumn.nodeParentId
        ? { columnId: this.currentColumn.nodeParentId, isDataScope: true }
        : { columnId: 0, columnName: this.parentColumnName, isDataScope: true };
      columnApi.columnLazyAntdvAll(param).then((res) => {
        this.treePopover = res.data;
      });
    },
  },
  watch: {
    addgoodsinfo: {
      handler(newVal, oldVal) {
        // 当addgoodsinfo发生变化时执行的逻辑
      },
      deep: true, // 如果addgoodsinfo是一个对象，需要加上deep:true
    },
  },
};
</script>
<style lang="scss" scoped>
.goodsdetailbox {
  min-height: 1050px;
}
::v-deep .uoloadSty .el-upload--picture-card {
  width: 150px;
  height: 150px;
  line-height: 150px;
}
::v-deep .disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
::v-deep .clearPadding .vxe-cell {
  　　padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
  　　padding-left: 0px;
}
::v-deep .tox-tinymce {
  min-height: 800px;
}
</style>
